class Joseph {
public:
    typedef struct ListNode ListNode;
    ListNode* buyNode(int x)
    {
        ListNode* newnode = new ListNode(x);
       
        return newnode;
    }

    ListNode* createList(int n)
    {
        ListNode* phead,*ptail;
        int i =1;
        phead = ptail = buyNode(i++);
        while(i <= n)
        {
            ptail->next = buyNode(i++);
            ptail = ptail->next;
        }

        ptail->next = phead;
        return phead;
    }

    int getResult(int n, int m) {
        ListNode* head = createList(n);
        ListNode* cur = head;
        ListNode* prev = nullptr;
        int i =1;
        while(cur->next != cur){
            if(i == m)
            {
                prev->next = cur->next;
                free(cur);
                cur = prev->next;
                i =1;
            }else
            {
                prev = cur;
                cur = cur->next;
                i++;
            }
        }

        return cur->val;
    }
};